<?php
namespace My\Controller;

use Utuo\BackgroundController;

class CategoryController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle("栏目管理");
		$this->setActionTitle(array(
			'index' => '栏目列表',
			'add' => '栏目添加',
			'modify' => '修改栏目',
			'recycle' => '回收站'
		));
		$this->setActionNav(array(
			'index',
			'add',
			'recycle'
		));
	}
	
	// 菜单列表
	public function indexAction() {
		$d = D("Category");
		$tree = $d->getTree(0, $this->aid,'id,pid,name,type,sort,status,is_deleted,logo,level,has_child');
		$categoryLists = $d->getTreeList($tree);
		foreach ($categoryLists as &$v){
			$v['type'] = $d->types[$v['type']];
		}
		$this->assign('categoryLists', $categoryLists);
		$this->display();
	}
	
	// 添加栏目
	public function addAction() {
		$d = D("Category");
		$pid = I("get.id",0,"intval");
		/*获得客户所有栏目*/
		$categoryOptions = array();
		$tree = $d->getTree(0, $this->aid,'id,pid,name,type,sort,status,is_deleted,logo,level,has_child');
		$categoryLists = $d->getTreeList($tree);
		foreach($categoryLists as $v) {
			$categoryOptions[$v['id']] = $v['tab'].$v['name'];
		}
		/*页面输出*/
		$this->assign("categoryOptions", $this->getOption($categoryOptions, "$pid", '==请选择父栏目=='));
		$this->assign("typesOptions", $this->getOption($d->types,'','==请选择栏目类别=='));
		$this->display();
	}
	
	// 提交添加栏目
	public function addPostAction() {
		$d = D("Category");
		if ($d->create()) {
			if($d->pid){
				$pLevel = M("category")->where("id=%d", $d->pid)->getField("level");
				$d->level = $pLevel + 1;
				D("Category")->where("id=%d",$d->pid)->setField('has_child',1);
			}
			$d->customer = $this->aid;
			$d->news = htmlspecialchars_decode($d->news);
			if ($d->add()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 修改栏目
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$d = D('Category');
		$this->checkAdmin(null, $d, "customer");
		$category = $this->getOneById('Category');
		/*获得客户所有栏目*/
		$categoryOptions = array();
		$tree = $d->getTree(0, $this->aid,'id,pid,name,type,sort,status,is_deleted,logo,level,has_child');		/*去除当前节点*/
		function delNode($id, &$now){
			foreach($now as $k=>&$v){
				if($v["id"] == $id){
					unset($now[$k]);
					return;
				}else{
					if($v["_"]) delNode($id, $v["_"]);
				}
			}
		}
		delNode($id, $tree);
		$categoryLists = $d->getTreeList($tree);
		foreach($categoryLists as $v) {
			$categoryOptions[$v['id']] = $v['tab'].$v['name'];
		}
		if($category['type'] == "list"){
			$modelList = M("Model")->getField('id,name');
		}else{
			$modelList = array();
		}
		/*页面输出*/
		$category['modelOptions'] = $this->getOption($modelList,$category['model'],"==请选择模型==");
		$category['categoryOptions'] = $this->getOption($categoryOptions, $category['pid'], '==请选择父栏目==');
		$category["typesOptions"] = $this->getOption($d->types,$category['type'],'==请选择栏目类别==');
		$this->assign("category", $category);
		$this->display();
	}
	
	// 提交修改栏目
	public function modifyPostAction() {
		$id = I("id", 0, "intval");
		$d = D("Category");
		if ($d->create()) {
			$d->customer = $this->aid;
			$d->news = htmlspecialchars_decode($d->news);
			/*父栏是否有变动*/
			$category = $this->getOneById("Category");
			$d->pid*=1;
			$m = M('Category');
			if($category['pid'] != $d->pid) { // 父栏有变动 
				
				/*验证修改后的栏目是否子级*/
				$tree = $d->getTree(0, $this->aid,'id,pid,name,type,sort,status,is_deleted,logo,level,has_child');
				function checkNode($old_pid, $new_pid, $now, $flag) {
					foreach($now as $k=>$v) {
						if($v["id"] == $old_pid){
							$flag = true; // 设置开始查找标识
							$now_pid = $v["pid"];
						}
						if($flag && ($v["pid"]===$now_pid) && $v["id"] != $old_pid) { // 已退出同级子树重设标识
							$flag = false;
							return false;
						}
						if($flag && ($v["id"] == $new_pid)){
							return true;
						}else{
							if($v["_"]) checkNode($old_pid, $new_pid, $v["_"], $flag);
						}
					}
				}
				if(checkNode($category['pid'], $d->pid, $tree, false)) {
					$this->ajaxError("新指定的父栏不能为当前栏目或其子级.{$category['pid']}--{$d->pid}");
				}
				
				/*更新原有父栏信息*/
				if(!$m->where('pid=%d and id!=%d',$category['pid'],$category['id'])->count()) { // 当前父栏已没有子栏
					$m->where('id=%d', $category['pid'])->setField('has_child',0);
				}
				
				/*设置当前指定的父栏有孩子*/
				$m->where('id=%d', $d->pid)->setField('has_child', 1);
				
				/*当前栏与子栏级别更新*/
				if($d->pid){
					$pLevel = $m->where("id=%d", $d->pid)->getField("level");
				}else{
					$pLevel = -1;
				}
				$m->where('id=%d', $id)->setField('level', ++$pLevel);
				$data = array($id);
				while($m->where(array("pid" => array("in", $data)))->count()) {
					$conditon = array("pid" => array("in", $data));
					$m->where($conditon)->setField("level", ++$pLevel);
					$data = $m->where($conditon)->getField("id", true);
				}
			}
			
			if (false !== $d->save()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 回收站
	public function recycleAction() {
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$condition = array(
				'is_deleted' => 1,
				'customer' => $this->aid
		);
		$categoryLists = M('Category')->where($condition)->limit($pagesize)->page($page)->order('id DESC')->select();
		$categoryCount = M('Category')->where($condition)->count();
		$this->assign('categoryLists', $categoryLists);
		$this->showPage($categoryCount, $pagesize);
		$this->display();	
	}
	
	// 恢复栏目
	public function restorePostAction() {
		$this->checkAdmin(null, M("Category"), "customer");
		$m = M("Category");
		$category = $this->getOneById('Category');
		// 有父栏先恢复父栏
		if($category['pid']){
			$parentCategory = $m->find($category['pid']);
			if($parentCategory['is_deleted']){
				$this->ajaxError("存在父栏目必须先恢复父栏目.");
			}
		}
		$this->ajaxRestore('Category');
	}
	
	// 移除栏目
	public function removePostAction() {
		$id = I('id', 0, 'intval');
		$m = M("Category");
		$this->checkAdmin(null, M("Category"), "customer");
		// 有子栏则不能删除
		if($m->where("pid=%d and is_deleted=0",$id)->count()) {
			$this->ajaxError("存在子栏目未能删除");
		}
		$this->ajaxRemove();
	}
	
	// 删除栏目
	public function deletePostAction() {
		$id = I('id', 0, 'intval');
		$m = M("Category");
		$this->checkAdmin(null, $m, "customer");
		// 有子栏则不能删除
		if($m->where("pid=%d",$id)->count()){
			$this->ajaxError("存在子栏目未能删除");
		}
		// 设置父栏无孩子
		$category = D("Category")->where("id=%d",$id)->find();
		if($category['pid']) D("Category")->where("id=%d",$category['pid'])->setField('has_child',0);
		$this->ajaxDelete('Category');
	}
	
	// 设置状态
	public function setStatusPostAction() {
		$this->checkAdmin(null, M("Category"), "customer");
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$category = M("Category");
		if ($category->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($category->getError());
		}
	}
	
	// 文件上传
	public function uploadAction() {
		$upload = new \Utuo\Upload();
		$info = $upload->uploadOne();
		if (!$info) {
			$this->ajaxError($upload->getError());
		}else{
			$this->ajaxSuccess("上传成功", $info);
		}
	}
	
	// 获取内容模型列表
	public function getModelListsPostAction() {
		$modelLists = M('model')->getField('id,name');
		echo $this->getOption($modelLists,I('modelId',0,'intval'),'==请选择内容模型==');
	}
	
	public function getTplListAction() {
		$type = I('type', 0);
		if( $type ) {
			// M("ThemeTplAuth")->where(array(''))
		}
	}
	
	
	
}